package com.joymart.prepaid.wallet.service;

import com.joymart.common.model.Range;
import com.joymart.common.system.BusinessConfig;
import com.joymart.common.system.IdGenerator;
import com.joymart.common.utils.DatetimeUtils;
import com.joymart.compute.model.OrderGain;
import com.joymart.compute.model.PvSumWithOwnerId;
import com.joymart.compute.repository.OrderGainRepository;
import com.joymart.compute.service.OrderGainService;
import com.joymart.prepaid.wallet.model.PrepaidWallet;
import com.joymart.prepaid.wallet.repo.PrepaidWalletRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jdbc.core.JdbcAggregateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.MathContext;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Transactional
public class PrepaidWalletService {

    @Autowired
    private JdbcAggregateTemplate jdbcAggregateTemplate;
    @Autowired
    private OrderGainRepository orderGainRepository;
    @Autowired
    private PrepaidWalletRepository prepaidWalletRepository;
    @Autowired
    private BusinessConfig businessConfig;

    public PrepaidWallet findByUserId(String userId) {
        return jdbcAggregateTemplate.findById(userId, PrepaidWallet.class);
    }

    public void create(PrepaidWallet prepaidWallet){
        prepaidWallet.setCreatedAt(DatetimeUtils.now());
        prepaidWallet.setBalance(BigDecimal.ZERO);
        jdbcAggregateTemplate.insert(prepaidWallet);
    }

    public void increase(String userId, BigDecimal amount){
        //todo 变动记录
        PrepaidWallet pw = jdbcAggregateTemplate.findById(userId, PrepaidWallet.class);
        pw.setBalance(pw.getBalance().add(amount, MathContext.DECIMAL64));
        jdbcAggregateTemplate.update(pw);
    }

    public void decrease(String userId, BigDecimal amount){
        this.increase(userId, amount.negate());
    }

    /**
     * 区间内订单收益转换为预付货款
     * 只限批发和代理的收益
     * 合营部分是年底分红
     */
    public void convertOrderGainToPrepaidWallet(Range range){
        convertOrderGainToPrepaidWallet(range, OrderGain.Type.AG_WHS_GAIN);
        convertOrderGainToPrepaidWallet(range, OrderGain.Type.AU_WHS_GAIN);
        convertOrderGainToPrepaidWallet(range, OrderGain.Type.AG_AGENT_GAIN);
        convertOrderGainToPrepaidWallet(range, OrderGain.Type.AU_AGENT_GAIN);
    }

    private void convertOrderGainToPrepaidWallet(Range range, OrderGain.Type type) {
        List<PvSumWithOwnerId> items = orderGainRepository.aggregateOrderPvGainOfAll(type, range.getStart(), range.getEnd());
        items.forEach(item->{
            this.increase(item.getOwnerId(), item.getPvSum().multiply(businessConfig.getPvCashRate(), MathContext.DECIMAL64));
        });
    }


}
